package persistent;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;

import frame.Frame;

public class PersistentServer  extends Thread {

	private static final int PORT_PAINTER_RECEP = 5825;
	
	protected ServerSocket serverSocket = null;
	protected BufferedReader in = null;
	protected boolean active = true;
	private SimpleDateFormat fmt;
	
	public PersistentServer(String name) throws IOException {
		super(name);
		serverSocket = new ServerSocket(PORT_PAINTER_RECEP);
		fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
	}
	
	public void run(){
		
		File log = new File("PersistLog.txt");
		while(active){
			
			try{
				
				Socket frameSocket = serverSocket.accept();
				InputStream is = frameSocket.getInputStream(); 
				ObjectInputStream ois = new ObjectInputStream(is);
				
				Frame f = (Frame)ois.readObject(); 
				
				PersitentSave(f, log);
			
			}
			catch(IOException e){
				e.printStackTrace();
			} 
			catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void PersitentSave(Frame fr, File Archivo){
		
		try
		{
			FileWriter salvar = new FileWriter(Archivo, true);
			salvar.write("Vehiculo: ");
			salvar.write(fr.getCodVehiculo());
			salvar.write(" Evento: ");
			salvar.write(fr.getCodEvento());
			salvar.write(" Posicion: ");
			salvar.write(" lat: "+fr.getLatitud());
			salvar.write(" long: " +fr.getIgnicion());
			salvar.write(" Direccion: ");
			salvar.write(fr.getDireccion());
			salvar.write(" Fecha. ");
			salvar.write(fr.getFecha().toString());
			salvar.write("Velocidad: ");
			salvar.write(fr.getVelocidad());
			salvar.write("\n");
			salvar.close();
		}
		catch (Exception e)
		{
			
		}
	}

}
